<template>
  <el-form :model="form"
           ref="form"
           class="add-report-form"
           :rules="rules"
           v-loading="loading">
    <p>Name your new custom dashboard and select the widgets to be used in the dashboard on the next page.</p>

    <el-form-item prop="name"
                  :label="$t('custom.reports.name')">
      <el-input v-model="form.name"
                maxlength="70"
                :placeholder="$t('custom.reports.name')"></el-input>
    </el-form-item>
    <el-form-item prop="roleIdList"
                  :label="$t('custom.reports.role')">
      <el-select v-model="form.roleIdList"
                 filterable
                 clearable
                 multiple
                 collapse-tags
                 default-first-option
                 style="width:100%"
                 :placeholder="$t('custom.reports.role')">
        <el-option v-for="(item,index) in roleOptions"
                   :key="index"
                   :value="item.roleId"
                   :label="item.name"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="tagList"
                  :label="$t('custom.reports.tag')">
      <el-select v-model="form.tagList"
                 filterable
                 clearable
                 multiple
                 allow-create
                 collapse-tags
                 default-first-option
                 :placeholder="$t('custom.reports.tag')"
                 style="width: 100%;">
        <el-option v-for="(item,index) in tags"
                   :key="index"
                   :label="item.name"
                   :value="item.name"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="description"
                  :label="$t('custom.reports.description')">
      <el-input v-model="form.description"
                type="textarea"
                :maxlength="500"
                :rows="3"
                @keyup.enter.native.stop
                :placeholder="$t('custom.reports.description')"></el-input>
    </el-form-item>

    <el-form-item class="text-right">
      <el-button type="text"
                 @click="moreEditVisible = true"
                 v-if="$hasPermission('sys:report:moreedit') || $store.state.user.username.includes('mspbots.ai')"
                 size="small">{{ $t('custom.reports.moreedit') }}</el-button>
      <el-button size="small"
                 type="primary"
                 :loading="loading"
                 @click="onSave">{{ $t('custom.reports.continue') }}</el-button>
    </el-form-item>

    <el-dialog width="470px"
               :title="$t('custom.reports.moreedit')"
               :visible.sync="moreEditVisible"
               append-to-body
               custom-class="more-dialog"
               destroy-on-close>
      <el-form :model="form"
               v-loading="moreLoading"
               ref="moreForm"
               class="more-edit-dialog-form "
               :rules="rules"
               @submit.native.prevent
               label-position="top">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item prop="businessType"
                          :label="$t('custom.dataset.businessType')">
              <el-select v-model="form.businessType"
                         :placeholder="$t('custom.dataset.businessType')"
                         style="width: 100%;"
                         :disabled="!$hasPermission('sys:tenant:model:allowtomanagesystemmodel')">
                <el-option v-for="item in businessTypes"
                           :key="item.dictValue"
                           :label="item.dictLabel"
                           :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="status"
                          :label="$t('custom.dataset.status')">
              <el-select v-model="form.status"
                         :placeholder="$t('custom.dataset.status')"
                         style="width: 100%;"
                         :disabled="!$hasPermission('sys:tenant:model:allowtomanagesystemmodel')">
                <el-option v-for="item in statusList"
                           :key="item.dictValue"
                           :label="item.dictLabel"
                           :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="tenantCode"
                          :label="$t('custom.dataset.tenantCode')">
              <SelectClientId v-model="form.tenantCode"
                              :disabled="form.businessType==='Template' || form.businessType==='MSPbots Internal'"
                              :width="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="da"
                          :label="$t('custom.report.da')">
              <el-select v-model="form.da"
                         clearable
                         filterable
                         :placeholder="$t('custom.report.da')"
                         style="width: 100%;">
                <el-option v-for="items in users"
                           :key="items.id"
                           :label="items.realname"
                           :value="items.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="po"
                          :label="$t('custom.report.po')">
              <el-select v-model="form.po"
                         clearable
                         filterable
                         :placeholder="$t('custom.report.po')"
                         style="width: 100%;">
                <el-option v-for="items in users"
                           :key="items.id"
                           :label="items.realname"
                           :value="items.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="jiraNumber"
                          :label="$t('custom.reports.jiraNumber')">
              <el-input v-model="form.jiraNumber"
                        type="text"
                        style="width: 100%"
                        rows="3"
                        :placeholder="$t('custom.reports.jiraNumber')">
                <JiraNumberLink slot="suffix"
                                :jiraNumber="form.jiraNumber" />
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item prop="progress"
                          :label="$t('custom.reports.progress')">
              <el-input v-model="form.progress"
                        :placeholder="$t('custom.reports.progress')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="eta"
                          :label="$t('custom.reports.eta')">
              <el-date-picker v-model="form.eta"
                              type="date"
                              style="width: 100%;"
                              :label="$t('custom.reports.eta')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="priority"
                          :label="$t('custom.reports.priority')">
              <el-select v-model="form.priority"
                         :placeholder="$t('custom.reports.priority')"
                         style="width: 100%;">
                <el-option label="High"
                           value="High"></el-option>
                <el-option label="Medium"
                           value="Medium"></el-option>
                <el-option label="Low"
                           value="Low"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="client"
                          :label="$t('custom.reports.client')">
              <el-input v-model="form.client"
                        type="textarea"
                        rows="2"
                        :placeholder="$t('custom.reports.client')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="uat"
                          :label="$t('custom.reports.uat')">
              <el-select v-model="form.uat"
                         :placeholder="$t('custom.reports.uat')"
                         style="width: 100%;">
                <el-option v-for="item in uatList"
                           :key="item.value"
                           :label="item.lable"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="overheadFilters"
                          :label="$t('custom.reports.overheadFilters')">
              <el-select v-model="form.overheadFilters"
                         :placeholder="$t('custom.reports.overheadFilters')"
                         style="width: 100%;">
                <el-option v-for="item in optionList"
                           :key="item.value"
                           :label="item.lable"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="reportingQa"
                          :label="$t('custom.reports.reportingQa')">
              <el-select v-model="form.reportingQa"
                         :placeholder="$t('custom.reports.reportingQa')"
                         style="width: 100%;">
                <el-option v-for="item in optionList"
                           :key="item.value"
                           :label="item.lable"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="allClientsQa"
                          :label="$t('custom.reports.allClientsQa')">
              <el-select v-model="form.allClientsQa"
                         :placeholder="$t('custom.reports.allClientsQa')"
                         style="width: 100%;">
                <el-option v-for="item in optionList"
                           :key="item.value"
                           :label="item.lable"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="internalNotes"
                          :label="$t('custom.reports.internalNotes')">
              <el-input v-model="form.internalNotes"
                        type="textarea"
                        rows="2"
                        :placeholder="$t('custom.reports.internalNotes')"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template slot="footer">
        <el-button @click="moreEditVisible = false"
                   :loading="moreLoading"
                   size="small">{{ $t('Cancel') }}</el-button>
        <el-button type="primary"
                   @click="onSave"
                   :loading="moreLoading"
                   size="small">{{ $t('Save') }}</el-button>
      </template>
    </el-dialog>
  </el-form>
</template>

<script>
import {
  fetchTag, fetchRole, fetchQuery, fetchAssignRole, fetchReport, cloneReport, matchJira
} from '@/api/new'
import { symbolReg } from '@/components/storybook/utilties/reg'
import useErrorMessage from '@/components/storybook/hooks/useErrorMessage'
import { intersectionBy } from 'lodash'
import { optionList, uatList } from '../index.schema'
import JiraNumberLink, { JiraNumberMixin } from '@/components/jira-number-link'
import { getGadget } from '@/components/storybook/hooks/useGadget'
import { v4 } from 'uuid'
import {filterRole} from '@/utils/common'
export default {
  name: 'AddReportForm',
  components: {
    JiraNumberLink

  },
  mixins: [JiraNumberMixin],
  props: {
    resourceType: [String, Number],
    id: {
      type: String,
      default: '1338420673936867329'
    },
    type:String,
    widgetInfo:{
      type: Object,
      default: () => ({})
    }
  },
  data () {
    const validateSymbol = (rule, value, callback) => {
      if (!symbolReg.test(value)) {
        return callback(new Error(this.$t('validate.isIncludeSymbol')))
      }
      callback()
    }

    return {
      form: {
      },
      rules: {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur', pattern: '[^ \x22]+' },
          { validator: validateSymbol, trigger: 'blur' },
          { min: 0, max: 69, message: this.$t('custom.tips.valueLength', { length: '70' }), trigger: 'change' },
          { validator: this.validateName, trigger: 'blur' }
        ],
        roleIdList: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        description: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { min: 0, max: 499, message: this.$t('custom.tips.valueLength', { length: '500' }), trigger: 'change' }
        ],
        po: [
          // { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        da: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        jiraNumber: [
          // { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          // { validator: this.validateJira, trigger: 'blur' }

        ],
        tenantCode: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ]
      },

      loading: false,
      moreLoading: false,
      moreEditVisible: false,
      optionList,
      uatList,
      roles: [],
      tags: [],
      users: [],
      roleOptions: [],
      assignRoles: [],
      businessTypes: [],
      statusList: [],
      cloneWidgetInfo: {},
    }
  },
  computed: {
    layoutType () {
      if (this.resourceType === 0 || this.resourceType === 100) {
        return this.type
      }
      if (this.resourceType === 2 || this.resourceType === 120) {
        return 'scorecard_layout'
      }
    }
  },
  created () {
    this.init()
  },
  methods: {
    async init () {
      try {
        this.loading = true
        const [roles, tags, assignRoles, users, businessTypes, statusList, report] = await Promise.all([
          this.getRoles(),
          this.getTags(),
          this.getAssingRoles(),
          this.getUsers(),
          this.getBusinessTypes(),
          this.getStatusList(),
          this.getReport()
        ])
        this.roles = roles
        this.tags = tags
        this.users = users
        this.assignRoles = assignRoles
        this.statusList = statusList
        this.businessTypes = businessTypes
        const assigns = this.assignRoles.map(item => ({
          ...item,
          roleId: item.assignId
        }))
        this.roleOptions = intersectionBy(this.roles, assigns, 'roleId')
        const { name, tenantCode, da, status, businessType, teamId = '', roleIdList: roleList, layoutType, ...rest } = report
        const defaultRoles = (this.$store.state.defaultRoleList || []).concat(['1539094477886771202','1603251831365554178'])
        const roleIdList = this.roleOptions.filter(({ roleId }) => defaultRoles.includes(roleId)).map(({ roleId }) => roleId)
        this.form = {
          ...rest,
          name: '',
          tenantCode: this.$store.state.user.tenantCode,
          da: this.$store.state.user.id,
          status: !this.$hasPermission('sys:report:moreedit') ? 'Published' : 'Requested',
          businessType: this.resourceType === 100 || this.resourceType === 120 ? 'MSPbots Internal' : 'Custom',
          teamId,
          roleIdList: roleIdList,
          layoutType: this.layoutType
        }
      } catch (error) {
      } finally {
        this.loading = false
      }
    },
    async getBusinessTypes () {
      const value = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_type_list')
      if (value) {
        const list = value.dataList || []
        if ((this.resourceType === 100 || this.resourceType === 120) && this.$hasPermission('sys:report:type:mspbots internal')) {
          return list.filter(item => item.dictValue === 'MSPbots Internal')
        }

        return list.filter(item => item.dictValue !== 'MSPbots Internal')
      }
      return []
    },
    async getStatusList () {
      const value = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_status_list')
      if (value) {
        const list = value.dataList || []
        if (this.$hasPermission('sys:reports:publishauth')) {
          return list
        }

        return list.filter(item => item.dictValue !== 'Alpha' && item.dictValue !== 'Published')
      }
      return []
    },
    async validateName (rule, value, callback) {
      try {
        const { businessType, tenantCode, layoutType } = this.form
        let params = {
          name: value.trim(),
          isNew: true,
          businessType,
          tenantCode,
          layoutType,
          reportId: ''
        }
        const { postCheckNameApi } = this.$interface.reports
        const { data: response } = await postCheckNameApi(params)
        if (response.code !== 0) {
          throw new Error('The name is already exists')
        }
        callback()
      } catch (error) {
        callback(error)
      }
    },
    async validateJira (rule, value, callback) {
      try {
        let params = {
          issueIdOrKey: value
        }

        const isMatchJiraNumber = await matchJira(params)
        if (!isMatchJiraNumber) {
          throw new Error(this.$t('custom.component.gadget.checkNumber'))
        }
        callback()
      } catch (error) {
        callback(error)
      }
    },
    async getRoles () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      const { data: response } = await fetchRole(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async getAssingRoles () {
      const roleIds = (this.$store.state.user.roleList || []).map(({ id }) => id)
      const params = {
        roleId: roleIds
      }
      const { data: response } = await fetchAssignRole(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async getTags () {
      const params = {
      }
      const { data: response } = await fetchTag(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async getUsers () {
      const params = {
        datasetKey: 'qwerdsafsadrtfzgsadfggs'
      }
      const { data: response } = await fetchQuery(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async getReport () {
      const { data: response } = await fetchReport(this.id)
      if (response.code !== 0) {
        throw response.msg
      }
      return response.data || {}
    },

    async onSave () {
      try {
        this.moreEditVisible ? this.moreLoading = true : this.loading = true

        await this.$refs[this.moreEditVisible ? 'moreForm' : 'form'].validate()

        await this.validateForm()
        if (this.widgetInfo&&this.widgetInfo.id) {
          await this.onClone()
        }

        const { id, ...rest } = this.form
        const params = {
          ...rest,
          reportId: id,
          id,
          layoutType: this.layoutType,
          resourceType: this.resourceType,
          cloneInfoList: [{ gadgetType: 'pageheadergadget' }]
        }
        const { data: response } = await cloneReport(params)
        if (response.code !== 0) {
          throw response.msg
        }
        this.$message.success(response.msg)
        if (this.cloneWidgetInfo&&this.cloneWidgetInfo.id) {
          localStorage.setItem(`cloneWightToDashboards-${response.data.id}`,JSON.stringify(getGadget(this.cloneWidgetInfo)))        
        }
       
        this.$emit('event:success', response.data)
      } catch (error) {
        useErrorMessage(error)
      } finally {
        this.moreEditVisible ? this.moreLoading = false : this.loading = false
      }
    },
    async validateForm () {
      const { da, po, jiraNumber, tenantCode, businessType, description } = this.form
      if (this.$store.state.user.username.includes('mspbots.ai') && this.$hasPermission('sys:report:moreedit')) {
        if (!da) {
          throw this.$t('custom.component.gadget.da')
        }
        if (!po) {
          throw this.$t('custom.component.gadget.po')
        }
        if (tenantCode === '1001' && businessType === 'Custom') {
          // eslint-disable-next-line no-throw-literal
          throw 'The login person is the default tenant, then the type of widget cannot be Custom.'
        }
        if (description.match(/^[ ]*$/)) {
          // eslint-disable-next-line no-throw-literal
          throw 'Description ' + this.$t('validate.required')
        }
        if (jiraNumber !== 'NA') {
          let params = {
            issueIdOrKey: jiraNumber
          }

          const isMatchJiraNumber = await matchJira(params)
          if (!isMatchJiraNumber) {
            throw this.$t('custom.component.gadget.checkNumber')
          }
        }
      }
    },
    async onClone () {
      try {
        let widgetInfo =  this.widgetInfo
        if (
          this.$store.state.user.username.includes('mspbots.ai') &&
          this.$hasPermission('sys:widget:moreedit')
        ) {
          if (!widgetInfo.da) {
            return this.$message.error(this.$t('custom.component.gadget.da'))
          }
          if (!widgetInfo.po) {
            return this.$message.error(this.$t('custom.component.gadget.po'))
          }
         
          if (!widgetInfo.jiraNumber) {
            return this.$message.error(
              this.$t('custom.component.gadget.checkNumber')
            )
          }
        }
       
        const { postWidgetCloneDataApi } = this.$interface.reports
 
        const params = {
          ...widgetInfo,
          name: `${widgetInfo.name}_clone_${moment().utc().format()}`,
          resourceType: 1,
          gadgetId: v4()
        }
        params.roleIdList = await filterRole(params.roleIdList)
        const { data: response } = await postWidgetCloneDataApi(params)
        if (response.code !== 0) {
          throw response.msg
        }
        this.cloneWidgetInfo = response.data      

      } catch (error) {
        console.log(error);
      }
    },

  }
}
</script>

<style lang="scss">
.more-dialog {
  .el-dialog__body {
    padding: 20px 0 20px 20px;
  }
}
.more-edit-dialog-form {
  height: 400px;
  padding-right: 15px;
  overflow: auto;
  .el-row {
    margin: 0;
  }

  &::-webkit-scrollbar {
    width: 5px;
    height: 5px;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background-color: #17b3a3;
    background-image: -webkit-linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.4) 25%,
      rgba(255, 255, 255, 0.4)
    );
  }

  &::-webkit-scrollbar-track {
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
    border-radius: 10px;
  }
}
</style>
